package com.dream.auth.service.impl;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import com.dream.auth.entity.SysUser;
import com.dream.auth.mapper.SysUserMapper;
import com.dream.auth.model.LoginRequest;
import com.dream.auth.model.LoginResponse;
import com.dream.auth.model.UserInfo;
import com.dream.auth.security.JwtUtils;
import com.dream.auth.service.AuthService;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

	private final AuthenticationManager authenticationManager;

	private final JwtUtils jwtUtils;

	private final SysUserMapper sysUserMapper;

	@Override
	public LoginResponse login(LoginRequest request) {
		// 认证
		Authentication authentication = authenticationManager
				.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));

		// 创建并保存SecurityContext
		SecurityContext context = SecurityContextHolder.createEmptyContext();
		context.setAuthentication(authentication);
		SecurityContextHolder.setContext(context);

		// 生成JWT
		UserDetails userDetails = (UserDetails) authentication.getPrincipal();
		String token = jwtUtils.generateToken(userDetails);

		// 获取用户信息
		SysUser user =
				sysUserMapper.selectOne(new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<SysUser>()
						.eq(SysUser::getUsername, userDetails.getUsername()));

		// 构建响应
		UserInfo userInfo =
				UserInfo.builder().id(user.getId()).username(user.getUsername()).nickname(user.getNickName()).build();

		return LoginResponse.builder().token(token).userInfo(userInfo).build();
	}
}